class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        srand(time(nullptr));
        return qsort_topk(nums, 0, nums.size() - 1, k);
    }

    int qsort_topk(vector<int>& nums, int begin, int end, int k)
    {
        if(begin == end)
            return nums[begin];
        
        int r = rand();
        int key = nums[r % (end - begin + 1) + begin];
        int i = begin, left = begin - 1, right =  end + 1;
        while(i < right)
        {
            if(nums[i] < key)
                swap(nums[++left], nums[i++]);
            else if(nums[i] == key)
                ++i;
            else
                swap(nums[--right], nums[i]);
        }

        int c = end - right + 1, b = right - left - 1;
        if(c >= k)
            return qsort_topk(nums, right, end, k);
        else if(b + c >= k)
            return key;
        else
            return qsort_topk(nums, begin, left, k - b - c);
    }
};
/*
//把整个数组建成一个大堆，(O(N))
//然后pop（k-1）次堆顶的元素后(log(N*K))
//堆顶的元素就是第k大的数
class Solution {
public:
    int findKthLargest(vector<int>& nums, int k) {
        priority_queue<int> MaxHeap(nums.begin(),nums.end());

        while(--k)
        {
            MaxHeap.pop();
        }
        return MaxHeap.top();
    }
};
*/